import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Modal, Select, Divider, Upload, Button, message, Table, Space, DatePicker, InputNumber, Spin } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { addRule, searchexamList, getstudents, searchsteaList, addstudent, getclassList, importClass, studentDel } from '../service';
import Grade from './grade';
import moment from 'moment'
import { value } from 'numeral';
const { Option } = Select;
const FormItem = Form.Item;

const CreateForm = props => {
  // 搜索实验
  const [classvalue, setclassvalue] = useState('')
  const [teachdata, setteachdata] = useState([])
  const [classfetch, setclassfetch] = useState(false)
  const [lastFetchId, setlastFetchId] = useState(0)

  const [remark, setremark] = useState(false)
  const [exam, setexam] = useState('')
  const [stulist, setstulist] = useState([])
  // 搜索学生
  const [searchstulist, setsearchstulist] = useState([])
  const [stuvalue, setstuvalue] = useState('')
  // 导入班级学生
  const [classselectedRowKeys, setclassselectedRowKeys] = useState([]);
  const [classlist, setclasslist] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [createModalVisible, handleModalVisible] = useState(false);//z增加学生
  const [gradeVisible, setgradeVisible] = useState(false);//成绩查询弹框
  const [addclass, setAddclass] = useState(false);//增加班级
  const [endtime, setendtime] = useState('');//增加班级
  let query = useRef({
    pageIndex: 1,
    pageSize: 20,
  })
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    pageSize: query.current.pageSize,
    total: 0,
    onChange: (pageIndex, pageSize) => {
      query.current = { ...query.current, pageIndex, pageSize }
      console.log(query.current)
      getlist(current.id)


    },

    onShowSizeChange: (pageIndex, pageSize) => {
      query.current = { ...query.current, pageIndex, pageSize }
      getlist(current.id)

    }
  };
  // 经 Form.useForm() 创建的 form 控制实例，不提供时会自动创建
  const [form] = Form.useForm();
  // 把父组件方法和属性传递过来到子组件
  const { modalVisible, onSubmit, onCancel, current } = props;
  // 点击确定的增加方法，里面调用了父组件的方法 触发表单验证收集value值
  const okHandle = async () => {
    // 判断提交
    const fieldsValue = await form.validateFields();
    if (moment(new Date())>moment(fieldsValue.start_times)) {
      message.error('考试开始时间不能晚于当前时间');
        return;
     }
    var obj = {}
    console.log(form, fieldsValue)
    if (fieldsValue) {
      obj.exam_time = fieldsValue.exam_time
      obj.experiment_id = fieldsValue.experiment_id
      obj.exam_name = fieldsValue.exam_name
      let info = JSON.parse(sessionStorage.getItem('account'))
      obj.start_time = moment(fieldsValue.start_times).format('YYYY-MM-DD hh:mm:ss')
      obj.end_time = endtime
      obj.admin_username = info.username
      console.log(fieldsValue, info)
    }
    // 利用父组件传递过来的方法，顺便传此子组件的值。进行调用
    onSubmit(obj);
  };

  useEffect(()=>{
    fetchUser('')
    if (form && !modalVisible) {
      // 每一次刷新都重置一次
      form.resetFields();
    }
  
  },[modalVisible])
  useEffect(() => {
    // 如果有props.current的值才会执行这个
    if (current) {
      console.log(current)
      current.start_times = moment(current.start_time)
      form.setFieldsValue({
        ...current,
      });
      setexam(current)
      getlist(current.id)
      setclassvalue(current.expersiment_name)
      setendtime(current.end_time)
      // console.log(current, form, props.current)
    }
  }, [props.current]);
  const getlist = async (id) => {
    var obj = { examId: id }
    const res = await getstudents({ ...query.current, ...obj })
    setstulist(res.data.list)
    paginationProps.total = res.data.total

  }
 
  // 查询成绩孙组件成绩信息
  const findgrade = async fields => {
    const hide = message.loading('正在查询');
    console.log(1111)
    try {
      var a = await addRule({
        desc: fields.desc,
      });
      console.log(a)
      hide();
      message.success('查询成功');
      return true;
    } catch (error) {
      hide();
      message.error('查询失败请重试！');
      return false;
    }
  };
  //查询
  const fetchUser = async value => {
    console.log('fetching user', value);
    setlastFetchId(lastFetchId + 1);
    const fetchId = lastFetchId;
    setteachdata([])
    setclassfetch(true)
    const datas = await searchexamList({ name: value })
    if (fetchId !== lastFetchId) {
      // for fetch callback order
      return;
    }

    setteachdata(datas.data)
    if (!current) {
      let a =datas.data
      let item =a[0]
       form.setFieldsValue({'exam_time':30})
       setclassvalue(item.experiment_name)
       form.setFieldsValue({'experiment_id':item.id})
       setremark(item.remark)

    }


  };
  const handleChange = (value, option) => {
    console.log(value, option)
    setremark(option.key)
    setclassvalue(option.children)
    form.setFieldsValue({ 'experiment_id': value })
  };
  // 选择框
  const onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setSelectedRowKeys(selectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const disabledDate = (current) => {
    // 不能选今天和今天之前的日期
    return current && current < moment().subtract(1, 'days') || current > moment().add(1, 'years');
  };
  const changeendtime = (val) => {
    var starttime = form.getFieldValue('start_times')
    // console.log(val,starttime, moment().add(30, 'minutes').format('YYYY-MM-DD hh:mm:ss'))
    let endtime = moment(starttime).add(val, 'minutes').format('YYYY-MM-DD hh:mm:ss')
    setendtime(endtime)
    form.setFieldsValue({ 'exam_time': val })
  }
  const changetime = (val1, val2) => {
    console.log(form.getFieldValue('exam_time'))

    if (form.getFieldValue('exam_time')) {

      let endtimes = moment(val2).add(form.getFieldValue('exam_time'), 'minutes').format('YYYY-MM-DD hh:mm:ss')
      setendtime(endtimes)
      console.log(endtimes, endtime, form.getFieldValue('exam_time'))

    }
  }
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '学号',
      dataIndex: 'student_number',
      key: 'student_number',
    },
    {
      title: '年纪',
      dataIndex: 'grade',
      key: 'grade',
    },
    {
      title: '班级',
      dataIndex: 'class_name',
      key: 'class_name',
    },

    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          {/* <a onClick={() => setgradeVisible(true)}>成绩查询</a> */}
          <a onClick={() => {del1(record) }}>删除</a>
        </Space>
      ),
    },
  ];
  // 导入学生到考试的导入按钮
  // 添加学生
  const searchstu = async (value) => {
    const datas = await searchsteaList({ name: value })
    setsearchstulist(datas.data)

  }
  const changestu = (key, val) => {
    setstuvalue(val)
  }
  // 考试成员添加
  const showModal = () => {
    // 检测是否开始或者结束
    var a = moment(current.end_time).isBefore(new Date())
    var b = moment(current.start_time).isAfter(new Date());
    var c = moment(new Date()).isBetween(current.start_time, current.end_time );
    if (a) {
        message.error('考试已结束，无法添加')
    }else if (b) {
      handleModalVisible(true)

    }else{
      message.error('考试进行中，无法添加')
    }
  };

  const hideModal = async () => {
    handleModalVisible(false)
    // 提交id
    const res = await addstudent({ examId: current.id, adminId: stuvalue.value })
    console.log(res.code)

    if (res.code == 200) {
      getlist(current.id)
    }

  };
  let classquery = useRef({
    pageIndex: 1,
    pageSize: 20,
    name: "",
  })
  const classpaginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    pageSize: classquery.current.pageSize,
    total: classlist.total,
    onChange: (pageIndex, pageSize) => {
      classquery.current = { ...classquery.current, pageIndex, pageSize }
      showaddclass(true)

    },

    onShowSizeChange: (pageIndex, pageSize) => {
      classquery.current = { ...classquery.current, pageIndex, pageSize }
      showaddclass(true)

    }
  };

  // 导入班级添加

  const showaddclass = async () => {
    var a = moment(current.end_time).isBefore(new Date())
    var b = moment(current.start_time).isAfter(new Date());
    var c = moment(new Date()).isBetween(current.start_time, current.end_time );
    if (a) {
        message.error('考试已结束，无法添加')
        return;
    }else if (b) {
      setAddclass(true)
      // 获取班级列表
      let res = await getclassList(classquery.current)
      console.log(res)
      setclasslist(res.data)
    }else{
      message.error('考试进行中，无法添加')
      return;
    }
  

  };

  const hideaddclass = async () => {
    setAddclass(false)
    // 提交id
    let ids = classselectedRowKeys.join(',')
    console.log(ids)
    let res = await importClass({ classId: ids, examId: current.id })
    console.log(res)
    if (res.code == 200) {
      message.success(res.message)
      getlist(current.id)
    }else if (res.code == 500) {
      message.error(`以下成员已参加过考试:${res.data}`)
    }
  };

  // 删除当前考试的成员
  const deleteItem1 = async (id) => {
    let res = await studentDel({ adminId: id, examId: current.id }).then(res=>{
      if (res.code == 200) {
        getlist(current.id)
      }

    })
  };
  const del1 = (currentItem) => {
    var a = moment(current.end_time).isBefore(new Date())//已结束
    var b = moment(current.start_time).isAfter(new Date());//未开始
    var c = moment(new Date()).isBetween(current.start_time, current.end_time );
    if (a) {
        message.error('考试已结束，无法删除')
        return;
    }else if (c) {
      message.error('考试进行中，无法删除')
      return;
    }
  
    let str = ''
    if (currentItem) {
      str = currentItem.id
    } else {
      //字符串拼接
      str = selectedRowKeys.join(',')
    }
    let content = currentItem? `\n确定要取消 ${currentItem.name +' __ '+currentItem.student_number} 考试资格吗？` : `本次选中 ${selectedRowKeys.length} 个学生，\n确定要删除吗？`
    console.log(currentItem, str)
    Modal.confirm({
      title: '删除任务',
      content: content,
      okText: '确认',
      cancelText: '取消',
      onOk: () => deleteItem1(str),
    });
  }
  // 选择框
  const onclassSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setclassselectedRowKeys(selectedRowKeys);
  };
  const classrowSelection = {
    classselectedRowKeys,
    onChange: onclassSelectChange,
  };


  const classcolumns = [
    {
      title: '班级代码',
      dataIndex: 'class_code',

    },

    {
      title: '年纪',
      dataIndex: 'grade',
    },
    {
      title: '班级',
      dataIndex: 'class_name',
    },
    {
      title: '人员',
      dataIndex: 'studentCount',
    },
  
  ]
  return (
    // 弹出对话框 destroyOnClose关闭时销毁model子元素 //onok点击确定回调
    <Modal
      destroyOnClose
      title={current ? '考试编辑' : '考试添加'}

      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
      okText="保存"
      cancelText="取消"
    >
      <Form form={form}>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="考试名称"
          name="exam_name"
          rules={[{ required: true, message: '必填信息' }]}

        >
          <Input placeholder="请输入" />
        </FormItem>

        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="选择实验"
          name="experiment_id"
          rules={[{ required: true, message: '必填信息!' }]}

          shouldUpdate={(prevValues, curValues) => prevValues.additional !== curValues.additional}

        >

          <Select
            showSearch
            defaultValue={current ? current.experiment_name : classvalue}
            value={classvalue}
            placeholder="Select exams"
            notFoundContent={classfetch ? <Spin size="small" /> : null}
            filterOption={false}
            onSearch={fetchUser}
            onChange={handleChange}
            style={{ width: '100%' }}
          >
            {teachdata.map(d => (
              <Option key={d.remark} value={d.id}>{d.experiment_name}</Option>
            ))}
          </Select>
          考试说明：{current ? current.remark : remark}
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="开始时间"
          name="start_times"
          rules={[{ required: true, message: '必填信息!' }]}
        >

          <DatePicker showTime disabledDate={disabledDate} format='YYYY-MM-DD hh:mm:ss' onChange={changetime} />


        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="时长/分钟"
          name="exam_time"
          rules={[{ required: true, message: '必填信息!' }]}
        >
          <InputNumber min={1}
            onChange={changeendtime}
            value={current ? current.exam_time : 30}
            style={{ 'width': '200px' }}
            formatter={value => `${value}`}
            parser={value => value.replace(/[^\d]/g, '')}
            precision={0} />
          <br />结束时间：{endtime}
        </FormItem>
      </Form>
      <div>

        <Grade
          onSubmit={async value => {
            // 子组件提交submit的时候执行这块代码区域，其中await 等他handleAdd有值的时候在执行下一步
            console.log(value)
            const success = await findgrade(value);
            if (success) {
              //   如果增加成功关闭打开框设置关闭
              setgradeVisible(false);
            }
          }}
          onCancel={() => setgradeVisible(false)}
          modalVisible={gradeVisible}
        />
        <Modal
          title="请输入学号或姓名："
          visible={createModalVisible}
          onOk={() => hideModal(false)}
          onCancel={() => hideModal(false)}
          okText="添加"
          cancelText="取消"
        >
          <div>
            <Select
              showSearch
              value={stuvalue.children}
              placeholder="请输入学号或姓名："
              filterOption={false}
              onSearch={searchstu}
              onChange={changestu}
              style={{ width: '100%' }}
            >
              {searchstulist.map(d => (
                <Option key={d.id} value={d.id}>{d.name + '-' + d.student_number}</Option>
              ))}
            </Select>

          </div>
        </Modal>
        {current ? <div>
          <Button type="primary" size='small' onClick={showModal}>
            添加
      </Button>
          <Divider type="vertical" />
          <Button type="primary" size='small' onClick={() => { showaddclass() }}>
            <UploadOutlined /> 班级导入
                           </Button>


          <Modal
            title="请选择班级,若无,请先绑定班级到当前用户"
            visible={addclass}
            onOk={() => { hideaddclass() }}
            onCancel={() => setAddclass(false)}
            okText="导入"
            cancelText="取消"
          >
            <Table rowSelection={classrowSelection} columns={classcolumns} dataSource={classlist.list} rowKey={record => record.id} pagination={classpaginationProps} />
          </Modal>
          <Divider type="vertical" />
          <Button type="primary" size='small' onClick={() => { del1() }}>
            删除
        </Button>
          <Table rowSelection={rowSelection} columns={columns} dataSource={stulist} pagination={paginationProps} rowKey={record => record.id} />

        </div> : ''}

      </div>

    </Modal>
  );
};

export default CreateForm;
